<?php
class ClsLTheme
{
    private $theme="default";
    private $themeDirectory="";
    private $themePath="";
    private $objModule=null;
    private $objController=null;
    private $forModule="";
    private $forAction="";
    private $module="";
    private $action="";
    private $isTemplate=true;
    private $isTemplateStrip=false;
    private $arrTplVar=array();
    private $errorMessage="";
    public function __construct($theme="default")
    {
        $this->theme=$theme;
        $this->themeDirectory=file_exists("themes/{$theme}/")?"themes/":NAANAL_PATH."themes/";
        $this->themePath="{$this->themeDirectory}{$this->theme}/";
        if(!file_exists($this->themePath))
        {
            $this->themePath=NAANAL_PATH."themes/default/";
        }
        $objRequest=ClsNaanalRequest::getInstance();
        $arrRequest=$objRequest->getAll();
        
        $this->module=$objRequest->getModule();
        $this->action=$objRequest->getAction();
        
        if($this->theme===false)
        {
            $this->isTemplate=false;
            $this->isTemplateStrip=true;
        }
        else
        {
            if(isset($arrRequest["template"]) && $arrRequest["template"]=="no")
            {
                $this->isTemplate=false;
                $this->isTemplateStrip=true;
            }
            else
            {
                $this->isTemplate=true;
                $this->isTemplateStrip=false;
            }
        }
        if($this->isTemplate===false)
        {
            $noTemplateTheme=getAppConfig("NO_TEMPLATE_THEME");
            if(!empty($noTemplateTheme))
            {
                $this->theme=$noTemplateTheme;
                $this->isTemplate=true;
            }
        }
        if(isset($arrRequest["template_strip"]) && $arrRequest["template_strip"]=="yes")
        {
            $this->isTemplate=false;
            $this->isTemplateStrip=true;
        }
        $this->arrTplVar["current_module"]=$this->module;
        $this->arrTplVar["current_action"]=$this->action;
    }
    public function setErrorMessage($errorMessage)
    {
        $this->errorMessage=$errorMessage;
    }
    public function setForModule($forModule)
    {
        $this->forModule=$forModule;
    }
    public function setForAction($forAction)
    {
        $this->forAction=$forAction;
    }
    public function setModuleObject(&$objModule)
    {
        $this->objModule=$objModule;
    }
    public function setControllerObject(&$objController)
    {
        $this->objController=$objController;
    }
    public function &getModuleObject()
    {
        return $this->objModule;
    }
    public function &getControllerObject()
    {
        return $this->objController;
    }
    public function setTemplateVariable($variable,$data)
    {
        $this->arrTplVar[$variable]=$data;
    }
    private function validateFile($tplPath)
    {
        if(!empty($this->arrTplVar)) extract($this->arrTplVar);
        
        $arrToken=token_get_all(file_get_contents($tplPath));
        $arrAllowedToken=array(311,367,316,370,315,369,T_VARIABLE);      
        $naanal_error=errMsg();
        foreach($arrToken as $ind=>$data)
        {
            $isAllowed=false;
            $isVariableError=false;
            $isFunctionError=false;
            if(!isset($data[2]) || in_array($data[0], $arrAllowedToken))
            {
                if($data[0]===T_VARIABLE)
                {
                    if(isset($this->arrConfigVar["template_variables"]) && in_array(substr($data[1],1), $this->arrConfigVar["template_variables"]))
                    {
                        $isAllowed=true;
                    }
                    else if($data[1]=='$theme_web_path' ||  $data[1]=='$theme_file_path' ||  $data[1]=='$form' || $data[1]=='$module' || $data[1]=='$action' || $data[1]=='$message' || $data[1]=='$formodule' || $data[1]=='$foraction' || $data[1]=='$naanal_error')
                    {
                        $isAllowed=true;
                    }
                    else
                    {
                        $isVariableError=true;
                    }
                }
                else if($data[0]===T_FUNCTION)
                {
                    $isFunctionError=true;
                }
                else
                {
                    $isAllowed=true;
                }
            }
            if($isVariableError)
            {
                $definedVar=$data[1];
                if($definedVar=='$_REQUEST' || $definedVar=='$_POST' || $definedVar=='$_GET' || $definedVar=='$_SESSION')
                {
                    $help="Usage of Super Globals such as \$_REQUEST, \$_POST, \$_GET and \$_SESSION are strictly restricted inside template";
                }
                else
                {
                    $definedVar=  substr($definedVar, 1);
                    $help="Variable other than defined in $page module's config.php is not allowed. If you need this variable define it in $page module's config.php. Ex.\$template_variables[]='{$definedVar}'";
                }
                traceDirect("File: {$tplPath}, Line No.: {$data[2]}, Variable '{$data[1]}' not allowed inside template. ".$help);
            }
            else if($isFunctionError)
            {
                die("File: {$tplPath}, Line No.: {$data[2]}, Function '{$data[1]}' not allowed inside template. ");
            }
        }
    }
    private function executeFile($naanal__file,$naanal__jsDir)
    {
        $naanal__arrVar=getJSConfig($naanal__jsDir);
        extract($naanal__arrVar);
        unset($naanal__arrVar);
        unset($naanal__jsDir);
        include $naanal__file;
        return get_defined_vars();
    }
    private function &renderTheme($tplPath,&$out)
    {
        if(!empty($this->arrTplVar)) extract($this->arrTplVar);
        $naanal_error=errMsg();
        $html_tag_head="<script type='text/javascript'>var URL_BASE_FILE_NAME='".URL_BASE_FILE_NAME."';</script>";
        
        $dir_handle=  opendir(NAANAL_PATH."js");
        $arrExecuteFile=array();
        while($file = readdir($dir_handle))
        {
            if($file=="." || $file=="..") continue;
            if(is_file(NAANAL_PATH."js/{$file}"))
            {
                continue;
            }
            if(!file_exists(NAANAL_PATH."js/{$file}/{$file}.php")) continue;
            $arrExecuteConfig=getJSConfig($file);
            if(!isset($arrExecuteConfig["priority"]))
            {
                $arrExecuteFile[0][]=$file;
            }
            else
            {
                $arrExecuteFile[(int)$arrExecuteConfig["priority"]][]=$file;
            }
        }
        ksort($arrExecuteFile,SORT_NUMERIC);
        foreach($arrExecuteFile as $arrFile)
        {
            foreach($arrFile as $file)
            {
                $this->executeFile(NAANAL_PATH."js/{$file}/{$file}.php",$file); 
            }
        }
        $arrScriptInclude=loadScriptFiles(false,false,false);
        $arrJSInclude=isset($arrScriptInclude["js"])?$arrScriptInclude["js"]:array();
        $arrCSSInclude=isset($arrScriptInclude["css"])?$arrScriptInclude["css"]:array();
        
        if(!empty($arrCSSInclude))
        {
            foreach($arrCSSInclude as $cssfile)
            {
                $html_tag_head=$html_tag_head."<link rel='stylesheet' href='{$cssfile}' type='text/css' />";
            }
        }
        if(file_exists("{$this->themePath}css/utils.css"))
        {
            $html_tag_head=$html_tag_head."<link rel='stylesheet' href='{$this->themePath}css/utils.css' type='text/css' />";
        }
        if(file_exists("{$this->themePath}css/{$this->theme}.css"))
        {
            $html_tag_head=$html_tag_head."<link rel='stylesheet' href='{$this->themePath}css/{$this->theme}.css' type='text/css' />";
        }
        if(file_exists("css/utils.css"))
        {
            $html_tag_head=$html_tag_head."<link rel='stylesheet' href='css/utils.css' type='text/css' />";
        }
        if(file_exists("modules/{$this->module}/css/utils.css"))
        {
            $html_tag_head=$html_tag_head."<link rel='stylesheet' href='modules/{$this->module}/css/utils.css' type='text/css' />";
        }
        if(file_exists("modules/{$this->module}/css/{$this->module}.css"))
        {
            $html_tag_head=$html_tag_head."<link rel='stylesheet' href='modules/{$this->module}/css/{$this->module}.css' type='text/css' />";
        }
        if(file_exists("modules/{$this->module}/css/{$this->action}.css"))
        {
            $html_tag_head=$html_tag_head."<link rel='stylesheet' href='modules/{$this->module}/css/{$this->action}.css' type='text/css' />";
        }
        
        if(!empty($arrJSInclude))
        {
            foreach($arrJSInclude as $jsfile)
            {
                $html_tag_head=$html_tag_head."<script src='{$jsfile}' type='text/javascript'></script>";
            }
        }
        if(file_exists("{$this->themePath}js/utils.js"))
        {
            $html_tag_head=$html_tag_head."<script src='{$this->themePath}js/utils.js' type='text/javascript'></script>";
        }
        if(file_exists("{$this->themePath}js/{$this->theme}.js"))
        {
            $html_tag_head=$html_tag_head."<script src='{$this->themePath}js/{$this->theme}.js' type='text/javascript'></script>";
        }
        if(file_exists("js/utils.js"))
        {
            $html_tag_head=$html_tag_head."<script src='js/utils.js' type='text/javascript'></script>";
        }
        if(file_exists("modules/{$this->module}/js/utils.js"))
        {
            $html_tag_head=$html_tag_head."<script src='modules/{$this->module}/js/utils.js' type='text/javascript'></script>";
        }
        if(file_exists("modules/{$this->module}/js/{$this->module}.js"))
        {
            $html_tag_head=$html_tag_head."<script src='modules/{$this->module}/js/{$this->module}.js' type='text/javascript'></script>";
        }
        if(file_exists("modules/{$this->module}/js/{$this->action}.js"))
        {
            $html_tag_head=$html_tag_head."<script src='modules/{$this->module}/js/{$this->action}.js' type='text/javascript'></script>";
        }
        $renderJS=ClsNaanalJS::renderModuleJS($this->module);
        $renderJS=trim($renderJS);
        if(!empty($renderJS))
        {
            $html_tag_head=$html_tag_head.$renderJS;
        }
        
        if(!empty($this->objController))
        {
            $arrHeaderData=$this->objController->getHeaderData();
            $title=isset($arrHeaderData["title"])?$arrHeaderData["title"]:"";
            $arrJSInclude=isset($arrHeaderData["js_include"])?$arrHeaderData["js_include"]:array();
            $arrCSSInclude=isset($arrHeaderData["css_include"])?$arrHeaderData["css_include"]:array();

            if($arrCSSInclude)
            foreach($arrCSSInclude as $css)
            {
                $html_tag_head=$html_tag_head."<link href='{$css}' rel='stylesheet' type='text/css' />";
            }

            if($arrJSInclude)
            foreach($arrJSInclude as $js)
            {
                $html_tag_head=$html_tag_head."<script src='{$js}' type='text/javascript'></script>";
            }

            unset($arrHeaderData);
            unset($arrJSInclude);
            unset($arrCSSInclude);
        }
        else
        {
            
        }
        $theme_web_path=$this->themePath;
        $error=$this->errorMessage;
        $login_name=  ClsNaanalSession::getInstance()->getPanelData("loginname");
        if($this->isTemplate && !empty($tplPath))
        {
            ob_start();
            include($tplPath);
            $out=ob_get_clean();
            return $out;
        }
        else
        {
            if($this->isTemplateStrip)
            {
                return $out;
            }
            else
            {
                $out=$html_tag_head."
".$out;
                return $out;
            }
        }
    }
    public function &render($out)
    {
        $tplPath="";
        $page=!empty($this->forModule)?$this->forModule:$this->module;
        $action=!empty($this->forAction)?$this->forAction:$this->action;
        /*if(!$this->isTemplate)
        {     
            return $out;
        }*/
        if($page=="home")
        {
            $objSession=ClsNaanalSession::getInstance();
            $isIntroStarted=$objSession->getPanelData("introStarted");
            if(!$isIntroStarted)
            {
                if(file_exists($this->themePath."intro.php"))
                {
                    $tplPath=$this->themePath."intro.php";
                }
            }
            if(empty($tplPath) && file_exists($this->themePath."home.php")&&!isLogged())
            {
                $tplPath=$this->themePath."home.php";
            }
        }
        
        if(empty($tplPath) && file_exists($this->themePath."inner.php"))
        {
            $tplPath=$this->themePath."inner.php";
        }
        $out=$this->renderTheme($tplPath,$out);
        return $out;
    }
    public static function &getInstance($theme="default")
    {
        static $arrTheme=array();
        if(!isset($arrTheme[$theme]))
        {
            $arrTheme[$theme]=new ClsLTheme($theme);
        }
        return $arrTheme[$theme];
    }
}
?>